﻿using System;
using NUnit.Framework;
using Smartkernel;
using Smartkernel.Caching;

namespace Smartkernel.NUnitTest.Caching
{
    [Category("Caching")]
    [TestFixture]
    public class SmartCacherValueTest
    {
        [Test]
        public void Test()
        {
            //【01】构造缓存对象，如果实际缓存对象为Null，将引发异常（涉及方法：构造函数）
            SmartAction.IsInvokeFail(delegate { new SmartCacherValue<object>(null, 100, true, 100); });

            //【02】如果对象被设置为刷新创建时间，则对象被访问时，应该更新创建时间（涉及方法：CreateTime属性、Value属性）
            SmartCacherValue<long> value1 = new SmartCacherValue<long>(DateTime.Now.Ticks, 100, true, 100);
            long ticks1 = value1.Value;
            DateTime dateTime1 = value1.CreateTime;
            System.Threading.Thread.Sleep(50);
            long ticks2 = value1.Value;
            DateTime dateTime2 = value1.CreateTime;
            Assert.AreEqual(dateTime2 > dateTime1, true);

            //【03】如果对象被设置为不刷新创建时间，则对象被访问时，创建时间不会改变（涉及方法：CreateTime属性、Value属性）
            SmartCacherValue<long> value2 = new SmartCacherValue<long>(DateTime.Now.Ticks, 100, false, 100);
            long ticks3 = value2.Value;
            DateTime dateTime3 = value2.CreateTime;
            long ticks4 = value2.Value;
            DateTime dateTime4 = value2.CreateTime;
            Assert.AreEqual(dateTime4, dateTime3);

            //【04】对象的调用计数器应该在被调用之后数值增大了（涉及方法：Counter属性）
            Assert.AreEqual(value1.Counter > 0, true);
            Assert.AreEqual(value2.Counter > 0, true);

            //【05】测试缓存对象是否超时（涉及方法：构造函数、IsOverdue属性）
            SmartCacherValue<long> value3 = new SmartCacherValue<long>(DateTime.Now.Ticks, 100, true, 0);
            Assert.AreEqual(value3.IsOverdue, false);

            SmartCacherValue<long> value4 = new SmartCacherValue<long>(DateTime.Now.Ticks, 1, true, 0);
            System.Threading.Thread.Sleep(1100);
            Assert.AreEqual(value4.IsOverdue, true);

            SmartCacherValue<long> value5 = new SmartCacherValue<long>(DateTime.Now.Ticks, 1, true, 0);
            System.Threading.Thread.Sleep(1100);
            long ticks5 = value5.Value;
            Assert.AreEqual(value5.IsOverdue, false);

            SmartCacherValue<long> value6 = new SmartCacherValue<long>(DateTime.Now.Ticks, 1, false, 0);
            System.Threading.Thread.Sleep(1100);
            long ticks6 = value6.Value;
            Assert.AreEqual(value6.IsOverdue, true);

            SmartCacherValue<long> value7 = new SmartCacherValue<long>(DateTime.Now.Ticks, 100, true, 10);
            Assert.AreEqual(value7.IsOverdue, true);

            SmartCacherValue<long> value8 = new SmartCacherValue<long>(DateTime.Now.Ticks, 100, true, 10);
            for (int i = 0; i < 15; i++)
            {
                long ticks7 = value8.Value;
            }
            Assert.AreEqual(value8.IsOverdue, false);
        }
    }
}
